<div class="col-sm-10">

    <div class="page-header" style="margin-top: 10px;
    margin-bottom: 5px;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #ddd;
    padding: 15px;">
        <h2 style="margin: 0px">查看简历</h2>
    </div>

    <div class="panel panel-default">
        <div class="panel-body">

            <div class="col-lg-12">
                <form class="form-horizontal" role="form">

                    <div class="form-group" style="visibility: hidden;">
                        <div class="single-cell">
                            <label for="employee_id" class="col-sm-1">*员工ID:</label>
                            <div class="col-sm-3">
                                <input type="text" class="form-control" name="employee_id" id="employee_id" disabled>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="resume_id" class="col-sm-1">*简历ID:</label>
                            <div class="col-sm-2">
                                <input type="text" class="form-control" name="resume_id" id="resume_id" disabled>
                                <span class="help-block"></span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="single-cell">
                            <label for="employee_name" class="col-sm-1">*姓名:</label>
                            <div class="col-sm-3">
                                <input type="text" class="form-control" name="employee_name" id="employee_name">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label class="col-sm-1">*民族:</label>
                            <div class="col-sm-1">
                                <select class="selectpicker show-tick form-control" id="nationSelect" name="nation"
                                        title="未选中" data-live-search="true"
                                        data-width="fit" data-size="5">
                                </select>
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <div class="col-sm-2">
                                <label>*性别:
                                    <input name="gender" type="radio" value="1" checked="checked">男
                                    <input name="gender" type="radio" value="2">女
                                </label>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="single-cell">
                            <label for="id_card" class="col-sm-1">*身份证件:</label>
                            <div class="col-sm-3">
                                <input type="text" class="form-control" name="id_card" id="id_card">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="birthday" class="col-sm-1">*出生日期:</label>
                            <div class="col-sm-3">
                                <input type="date" class="form-control" name="birthday" id="birthday">
                                <span class="help-block"></span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="single-cell">
                            <label for="phone" class="col-sm-1">*手机号码:</label>
                            <div class="col-sm-3">
                                <input type="email" class="form-control" name="phone" id="phone">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="email" class="col-sm-1">*电子邮件:</label>
                            <div class="col-sm-3">
                                <input type="email" class="form-control" name="email" id="email">
                                <span class="help-block"></span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="single-cell">
                            <label for="position_id" class="col-sm-1">*职位:</label>
                            <div class="col-sm-2">
                                <select id="position_id" name="position_id" class="selectpicker show-tick form-control">
                                    <option value="1">xx职位</option>
                                    <option value="2">yy职位</option>
                                    <option value="3">aa职位</option>
                                    <option value="4">bb职位</option>
                                    <option value="5">dd职位</option>
                                </select>
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="department_id" class="col-sm-1">*所属部门:</label>
                            <div class="col-sm-2">
                                <select id="department_id" name="department_id" class="selectpicker show-tick form-control">
                                    <option value="1">xx部门</option>
                                    <option value="2">yy部门</option>
                                    <option value="3">aa部门</option>
                                    <option value="4">bb部门</option>
                                    <option value="5">dd部门</option>
                                </select>
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="employ_time" class="col-sm-1">*上岗日期:</label>
                            <div class="col-sm-2">
                                <input type="date" class="form-control" name="employ_time" id="employ_time">
                                <span class="help-block"></span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="single-cell">
                            <label for="political_outlook" class="col-sm-1">*政治面貌:</label>
                            <div class="col-sm-2">
                                <select id="political_outlook" name="political_outlook" class="form-control">
                                    <option value="1">普通群众</option>
                                    <option value="2">共青团员</option>
                                    <option value="3">预备党员</option>
                                    <option value="4">中共党员</option>
                                </select>
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="marry_status" class="col-sm-1">*婚姻状况:</label>
                            <div class="col-sm-2">
                                <select id="marry_status" name="marry_status" class="form-control">
                                    <option value="1">未婚</option>
                                    <option value="2">已婚</option>
                                </select>
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="others_contact" class="col-sm-2">*其他联系方式:</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" name="others_contact" id="others_contact">
                                <span class="help-block"></span>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="single-cell">
                            <label for="urgent_people" class="col-sm-2">*紧急联系人:</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" name="urgent_people" id="urgent_people">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="urgent_phone" class="col-sm-2">*紧急联系电话:</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" name="urgent_phone" id="urgent_phone">
                                <span class="help-block"></span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="single-cell">
                            <label for="literacy" class="col-sm-1">*文化程度:</label>
                            <div class="col-sm-2">
                                <select id="literacy" name="literacy" class="form-control">
                                    <option value="1">小学</option>
                                    <option value="2">初中</option>
                                    <option value="3">高中</option>
                                    <option value="4">大专</option>
                                    <option value="5">本科</option>
                                    <option value="6">本科以上</option>
                                </select>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="address" class="col-sm-1">*户籍地址:</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" name="address" id="address">
                                <span class="help-block"></span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="single-cell">
                            <label for="graduated_school" class="col-sm-1">*毕业学校:</label>
                            <div class="col-sm-3">
                                <input type="text" class="form-control" name="graduated_school" id="graduated_school">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="graduated_time" class="col-sm-1">*毕业时间:</label>
                            <div class="col-sm-3">
                                <input type="date" class="form-control" name="graduated_time" id="graduated_time">
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="single-cell">
                            <label for="major" class="col-sm-1">*所学专业:</label>
                            <div class="col-sm-3">
                                <input type="text" class="form-control" name="major" id="major">
                                <span class="help-block"></span>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="single-cell">
                            <label class="col-sm-1">备注：</label>
                            <div class="col-sm-11">
                                <textarea class="form-control" id="remark" name="remark" rows="5"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="center-block">
                        <div class="col-sm-offset-5 col-sm-7">
                            <button type="button" id="test_btn" class="btn btn-info">测试按钮</button>
                            <button type="button" id="confirm_btn" class="btn btn-primary">确定</button>
                            <button type="button" id="back_btn" class="btn btn-info">返回</button>
                        </div>
                    </div>

                </form>
            </div>

        </div>
    </div>
</div>
<script>
    //定义一些页内变量
    //（部门列表（带职位列表））
    var departments;
    //bindOnEvent是否完成的标识
    var bindOnEvent_finish = false;
    //initPage是否完成的标识
    var initPage_finish = false;

    $(function () {
        startWaiting();
        //初始化页面
        initPage();
        //给控件绑定事件
        bindOnEvent();
        checkIsFinish();
    });

    /**
     * 该方法用于开始等待页面数据填充
     */
    function startWaiting() {
        //弹出等待模态框
        $('#wait_modal').modal({
            show: true,
            backdrop: 'static'
        });
    }

    /**
     * 该方法用于循环等待并判断是否已结束了页面加载，若是则结束，若否则继续等待
     */
    function checkIsFinish() {
        let intervalID = setInterval(function () {
            console.log("持续等待页面加载...");
            if (initPage_finish && bindOnEvent_finish) {//如果可以结束，则结束
                console.log("页面加载完成!");
                //关闭等待模态框
                $('#wait_modal').modal('hide');
                clearInterval(intervalID);//结束循环
            }
        }, 200);
    }

    /**
     * 初始化页面
     */
    function initPage() {
        //开始前先移除main里面的所有点击事件
        unbindAll();

        let empID = sessionStorage.getItem("empID");
        //如果ID不为空，则可以查询
        if (empID != null) {
            //发送员工ID请求查看简历
            $.ajax({
                url: resumeInterface,
                data: "emp_id=" + empID,
                type: "GET",
                beforeSend: function(XMLHttpRequest ) {
                    //在请求头部设置accessToken
                    XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                },
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    console.log("获取到的简历信息为：");
                    console.log(result);
                    //判断保存的状态，200为成功，400为失败
                    if (result.code == 200) {
                        let employee = result.dataMap.employee;//获取到员工信息
                        let resume = result.dataMap.resume;//获取到简历信息
                        showEmployee(employee);
                        showResume(resume);
                        showSpecial(employee, resume);
                    } else {
                        //提示保存失败
                        alertUtil.message("获取数据失败！", "danger");
                    }
                }, error: function () {
                    //提示保存失败
                    alertUtil.message("服务器后端未响应！", "danger");
                }, complete: function () {//该模块在完成后一定会被调用
                    initPage_finish = true;
                }
            });
        } else {//否则也不用返回，因为没有员工ID时也有可能是增加新员工的情况
            initPage_finish = true;
            let employee = {};//员工信息
            let resume = {};//简历信息
            showEmployee(employee);
            showResume(resume);
            showSpecial(employee, resume);
        }


    }

    /**
     * 该方法用于移除所有的点击事件(对于on托管的事件无效)
     */
    function unbindAll() {
        $("#main").find("*").each(function (index, item) {
            $(item).off();//移除点击事件
        });
    }

    /**
     * 该方法用于建造民族代码选框
     */
    function buildNationSelect(nationCode) {
        let $nationSelect = $("#nationSelect");

        $.ajax({//请求全部角色
            url: nationInterface,
            type: "GET",
            beforeSend: function(XMLHttpRequest ) {
                //在请求头部设置accessToken
                XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
            },
            //请求成功后的回调函数
            //result是请求成功后返回的Json结果
            success: function (result) {
                let nationList = result.dataMap.nations;//民族数据列表

                //遍历民族数据列表并加入下来菜单中
                $.each(nationList, function (index, item) {
                    let nationStr = (item.id >= 10 ? item.id : "0" + item.id) + "&nbsp;&nbsp;" + item.nation_name;

                    let $roleOp = $("<option></option>")
                        .addClass("nation_option")//加入一个识别用的类
                        .append(nationStr)
                        .attr("value", item.id);//创建选项框
                    $nationSelect.append($roleOp);//加入选项框
                });

                //初始化selectpicker
                $nationSelect.selectpicker({
                    'selectedText': 'cat',
                    'noneResultsText': "没有搜索结果匹配 {0} 关键字"//给搜索栏使用
                });
                let checkedNation = [];
                checkedNation.push(nationCode);
                $nationSelect.val(checkedNation);//进行勾选（勾选需要在初始化selectpicker之后）
                //不刷新则无法显示
                $nationSelect.selectpicker('refresh');
                $nationSelect.selectpicker('render');
            }
        });
    }

    /**
     * 该方法用于建造部门和职位选框
     */
    function buildPositionSelect(nowPositionId) {
        let $positionSelect = $("#position_id");
        let $departmentSelect = $("#department_id");

        $.ajax({//请求全部部门信息
            url: getAllDepartmentsWithPositions,
            type: "GET",
            beforeSend: function(XMLHttpRequest ) {
                //在请求头部设置accessToken
                XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
            },
            //请求成功后的回调函数
            //result是请求成功后返回的Json结果
            success: function (result) {
                departments = result.dataMap.departments;//部门数据列表
                let nowDepartmentId = departments[0].id;//目前需要被选中的部门Id(默认为第一个)
                let nowPositionList = departments[0].positionList;//目前需要被选中的部门的职位列表
                nowPositionId = (nowPositionId == undefined ? nowPositionList[0].id : nowPositionId);//目前需要被选中的职位Id(默认为第一个)

                //构建部门下拉框
                $departmentSelect.empty();//新增前先清空
                //遍历部门数据列表并加入下拉菜单中
                $.each(departments, function (index, item) {
                    //遍历职位列表，尝试找到需要被勾选的部门的Id
                    for (let i = 0; i < item.positionList.length; i++) {
                        //如果找到职位列表，就创建职位下拉框并进行默认勾选
                        if (nowPositionId == item.positionList[i].id) {
                            nowDepartmentId = item.id;
                            nowPositionList = item.positionList;
                            break;
                        }
                    }

                    let departmentStr = item.department_name;

                    let $departmentOp = $("<option></option>")
                        .addClass("department_option")//加入一个识别用的类
                        .append(departmentStr)
                        .attr("value", item.id);//创建选项框
                    $departmentSelect.append($departmentOp);//加入选项框
                });
                //初始化selectpicker
                $departmentSelect.selectpicker({
                    'selectedText': 'cat',
                    'noneResultsText': "没有搜索结果匹配 {0} 关键字"//给搜索栏使用
                });
                let checkedDepartment = [];
                checkedDepartment.push(nowDepartmentId);
                $departmentSelect.val(checkedDepartment);//进行勾选（勾选需要在初始化selectpicker之后）
                //不刷新则无法显示
                $departmentSelect.selectpicker('refresh');
                $departmentSelect.selectpicker('render');

                //构建职位下拉框
                $positionSelect.empty();//新增前先清空
                //遍历职位数据列表并加入下拉菜单中
                $.each(nowPositionList, function (index, item) {
                    let positionStr = item.position_name;
                    let $positionOp = $("<option></option>")
                        .addClass("department_option")//加入一个识别用的类
                        .append(positionStr)
                        .attr("value", item.id);//创建选项框
                    $positionSelect.append($positionOp);//加入选项框
                });
                //初始化selectpicker
                $positionSelect.selectpicker({
                    'selectedText': 'cat',
                    'noneResultsText': "没有搜索结果匹配 {0} 关键字"//给搜索栏使用
                });
                let checkedPosition = [];
                checkedPosition.push(nowPositionId);
                $positionSelect.val(checkedPosition);//进行勾选（勾选需要在初始化selectpicker之后）
                //不刷新则无法显示
                $positionSelect.selectpicker('refresh');
                $positionSelect.selectpicker('render');
            }
        });
    }

    /**
     * 该方法用于将员工数据展示出来
     */
    function showEmployee(employee) {
        //将员工id设置在员工框
        showInfo2Input("employee_id", sessionStorage.getItem("empID"));
        for (let key in employee) {
            showInfo2Input(key, employee[key]);
        }
    }

    /**
     * 该方法用于将简历数据展示出来
     */
    function showResume(resume) {
        try {
            let resumeID = resume.id;
            $("select[name='resume_id']").val(resumeID);
        } catch (e) {
        }
        for (let key in resume) {
            showInfo2Input(key, resume[key]);
        }
    }

    /**
     * 该方法用于将简历数据展示一些特殊的数据
     */
    function showSpecial(employee, resume) {
        let nationCode = (resume === null) ? 1 : resume.nation;
        buildNationSelect(nationCode);//构建民族代码选框
        buildPositionSelect(employee.position_id);//构建部门与职位选框
    }

    /**
     * 该方法用于将员工数据展示出来
     */
    function showInfo2Input(inputName, info) {
        switch (inputName) {
            case "id":
                break;
            case "nation":
                // buildNationSelect(info);
                break;
            case "gender":
                $.each($("input[name='" + inputName + "']"), function (index, item) {
                    if ($(item).val() == info)
                        $(item).attr('checked', 'checked');
                });
                break;
            case "literacy":
            case "political_outlook":
            case "marry_status":
                $("select[name='" + inputName + "']").val(info);
                break;
            default:
                $("input[name='" + inputName + "']").val(info);
                break;
        }
    }

    /**
     * 该方法用于在跳转前清空简历的数据
     */
    function clearResume() {
        sessionStorage.removeItem("empID");
    }

    /**
     * 该方法用于给控件下方的位置显示错误
     */
    function showSingleError(selectorName, errorMsg) {
        //添加错误显示并添加错误信息
        $("input[name='" + selectorName + "'],select[name='" + selectorName + "']").parents(".single-cell").addClass("has-error");
        $("input[name='" + selectorName + "'],select[name='" + selectorName + "']").parent().parent().find("span.help-block").append(errorMsg);
    }

    /**
     * 该方法用于给所有控件下方的位置清除错误
     */
    function clearAllErrors() {
        $("input,select").parents().removeClass("has-error");
        $("input,select").parent().parent().find("span.help-block").empty();
    }

    /**
     * 该方法用于获取页面的员工与简历的数据<br>
     * 返回的对象结构为<br>
     * employeeWithResumeData = {<br>
     *      employee: employee,<br>
     *      resume: resume<br>
     *  }
     */
    function getEmployeeWithResumeData() {
        let employee = {
            id: $("input[name='employee_id']").val(),
            employee_name: $("input[name='employee_name']").val(),
            id_card: $("input[name='id_card']").val(),
            birthday: $("input[name='birthday']").val(),
            gender: $("input[name='gender']").val(),
            position_id: $("select[name='position_id']").val(),
            status: $("input[name='status']").val(),
            resume_id: $("input[name='resume_id']").val()
        };

        let resume = {
            id: $("input[name='resume_id']").val(),
            employ_time: $("input[name='employ_time']").val(),
            literacy: $("select[name='literacy']").val(),
            marry_status: $("select[name='marry_status']").val(),
            political_outlook: $("select[name='political_outlook']").val(),
            nation: $("select[name='nation']").val(),
            address: $("input[name='address']").val(),
            phone: $("input[name='phone']").val(),
            email: $("input[name='email']").val(),
            others_contact: $("input[name='others_contact']").val(),
            urgent_people: $("input[name='urgent_people']").val(),
            urgent_phone: $("input[name='urgent_phone']").val(),
            graduated_school: $("input[name='graduated_school']").val(),
            graduated_time: $("input[name='graduated_time']").val(),
            major: $("input[name='major']").val(),
            remark: $("textarea[name='remark']").val()
        };

        let employeeWithResumeData = {
            employee: employee,
            resume: resume
        };

        return employeeWithResumeData;
    }

    function bindOnEvent() {
        //test_btn的点击事件
        $("#test_btn").off("click").click(function () {
            clearAllError();
        });

        //返回键的点击事件
        $("#back_btn").off("click").click(function () {
            //跳转前先清理
            clearResume();
            console.log("从简历页面返回中...");
            //加载上一个页面
            // $("#main").load(sessionStorage.getItem("lastUrl"));
            $.ajax({//跳转到简历部分
                url: sessionStorage.getItem("lastUrl"),
                type: "GET",
                beforeSend: function (XMLHttpRequest) {
                    //在请求头部设置accessToken
                    XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                },
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    $("#main").html(result);//加载网页
                },
                error: function () {
                    alertUtil.message("服务器后端未响应!", "danger");
                }
            });
        });

        //确定键的点击事件
        $("#confirm_btn").off("click").click(function () {
            // let employee_id = ;
            //使用自己写的获取员工和简历信息的api获取
            let employeeWithResumeData = getEmployeeWithResumeData();
            let employeeWithResumeJsonData = JSON.stringify(employeeWithResumeData);
            console.log("employeeWithResumeJsonData:" + employeeWithResumeJsonData);

            $.ajax({//请求保存该员工和他的简历
                url: resumeInterface,
                data: employeeWithResumeJsonData,
                contentType: 'application/json;charset=utf-8',
                type: "POST",
                beforeSend: function(XMLHttpRequest ) {
                    //在请求头部设置accessToken
                    XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                },
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    if (result.code == 200) {
                        clearAllError();//先清除所有错误
                        alertUtil.message(result.msg);
                    } else {
                        //获取错误信息对象
                        let errorMap = result.dataMap.fieldErrors;
                        //给输入框显示信息
                        console.info(errorMap);
                        clearAllError();//先清除所有错误
                        for (let inputName in errorMap) {//js原生遍历
                            console.log("错误信息为:" + inputName + ":" + errorMap[inputName]);//键值对
                            showSingleError(inputName, errorMap[inputName]);
                        }
                        alertUtil.message(result.msg, "danger");
                    }
                    //关闭模态框
                    // $('#update_role_modal').modal('hide');
                    //跳转到尾页
                    // to_page(sessionStorage.getItem("totalRecords"));
                },
                error: function () {
                    alertUtil.message("服务器后端未响应!", "danger");
                }
            });
        });

        //绑定部门选择框的刷新和改变选择的事件
        $(document).off("changed.bs.select", "#department_id")
            .on("changed.bs.select", "#department_id",
                function (e, clickedIndex, isSelected, previousValue) {
                    let $departmentSelect = $("#department_id");
                    let $positionSelect = $("#position_id");

                    let departmentId = $departmentSelect.val();
                    let positions;
                    //构建职位下拉选择框
                    $positionSelect.empty();//新增前先清空
                    //遍历部门列表，直到找到部门Id为departmentId的部门为止
                    for (let i = 0; i < departments.length; i++) {
                        if (departments[i].id == departmentId) {
                            positions = departments[i].positionList;
                            break;
                        }
                    }

                    //遍历职位数据列表并加入下拉菜单中
                    $.each(positions, function (index, item) {
                        let positionStr = item.position_name;

                        let $positionOp = $("<option></option>")
                            .addClass("position_option")//加入一个识别用的类
                            .append(positionStr)
                            .attr("value", item.id);//创建选项框
                        $positionSelect.append($positionOp);//加入选项框
                    });

                    //初始化selectpicker
                    $positionSelect.selectpicker({
                        'selectedText': 'cat',
                        'noneResultsText': "没有搜索结果匹配 {0} 关键字"//给搜索栏使用
                    });
                    //不刷新则无法显示
                    $positionSelect.selectpicker('refresh');
                    $positionSelect.selectpicker('render');
                });
        //绑定事件函数结束
        bindOnEvent_finish = true;
    }
</script>



